package com.hengyue.system.repository;

import com.hengyue.common.core.respository.BaseRepository;
import com.hengyue.system.domain.entity.SysUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Set;

@Repository
public interface UserRepository extends BaseRepository<SysUser, Long> {

    SysUser findByName(String name);

    @Query("SELECT r.id FROM SysUser u JOIN u.sysRoles r WHERE u.id = :userId")
    Set<Long>  findRoleIdsByUserId(@Param("userId") Long userId);

   /* @NotNull
    @EntityGraph(attributePaths = {"dept"})
    Page<SysUser> findAll(@NotNull Specification<SysUser> spec, @NotNull Pageable pageable);*/

    boolean existsByNameAndIdNot(String userName, Long excludeRoleId);

    boolean existsByPhoneNumberAndIdNot(String phoneNumber, Long excludeRoleId);

    @Modifying
    @Query(value = "DELETE FROM user_role WHERE user_id IN :userIds", nativeQuery = true)
    void deleteUserRoleRelations(@Param("userIds") Long[] userIds);

    @Modifying
    @Query("DELETE FROM SysUser u WHERE u.id IN :ids")
    void deleteAllByIdInBatch(@Param("ids") Collection<Long> ids);

}